<template>
  <div class="divBox">
    <el-card
      class="box-card"
      shadow="never"
      :bordered="false"
      :body-style="{ padding: 0 }"
    >
      <div class="padding-add">
        <el-form ref="form" inline :model="tableFrom" @submit.native.prevent>
          <el-form-item label="赛事名称：">
            <el-input
              v-model.trim="tableFrom.competitionName"
              placeholder="请输入赛事名称"
              class="selWidth"
              size="small"
              clearable
              @keyup.enter.native="getList(1)"
            ></el-input>
          </el-form-item>
          <el-form-item label="留言内容：">
            <el-input
              v-model.trim="tableFrom.context"
              placeholder="请输入留言内容"
              class="selWidth"
              size="small"
              clearable
              @keyup.enter.native="getList(1)"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getList(1)">查询</el-button>
            <el-button size="small" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="box-card mt14" :body-style="{ padding: '20px' }" shadow="never" :bordered="false">
      <el-button
        type="primary"
        class="mb20"
        size="small"
        @click="handlerAdd"
        >新增留言</el-button
      >
      <el-table v-loading="loading" :data="tableData.data" size="small">
        <el-table-column prop="id" label="ID" min-width="80" />
        <el-table-column label="赛事ID" min-width="100" prop="competitionId" />
        <el-table-column label="赛事名称" min-width="150" prop="competitionName" :show-overflow-tooltip="true" />
        <el-table-column label="留言内容" min-width="200" prop="context" :show-overflow-tooltip="true" />
        <el-table-column label="回答内容" min-width="200">
          <template slot-scope="scope">
            <span v-if="scope.row.child && scope.row.child.length > 0" :title="scope.row.child[0].context">
              {{ scope.row.child[0].context }}
            </span>
            <span v-else class="text-muted">暂无回答</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="150" prop="createTime" />
        <el-table-column label="审核状态" min-width="100" prop="checkStatus">
          <template slot-scope="scope">
            <el-tag 
              :type="scope.row.checkStatus === 1 ? 'success' : 'warning'"
              size="small"
            >
              {{ scope.row.checkStatus === 1 ? '已审核' : '未审核' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="address" fixed="right" width="300" label="操作">
          <template slot-scope="scope">
            <a @click="handleDetail(scope.row)">查看详情</a>
            <el-divider direction="vertical"></el-divider>
            <a 
              v-if="scope.row.checkStatus === 0"
              @click="handleCheck(scope.row)"
            >
              审核通过
            </a>
            <span v-else class="text-success">已审核</span>
            <el-divider direction="vertical"></el-divider>
            <a @click="handleAnswer(scope.row)">回答</a>
            <el-divider direction="vertical"></el-divider>
            <a @click="handleDelete(scope.row.id)">删除</a>
          </template>
        </el-table-column>
      </el-table>
      <div class="block-pagination">
        <el-pagination
          background
          :page-sizes="[20, 40, 60, 80]"
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @current-change="pageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" :before-close="handleClose">
      <el-form :model="formData" :rules="rules" ref="formData" label-width="100px" class="demo-ruleForm">
        <el-form-item label="赛事ID：" prop="competitionId">
          <el-input-number
            v-model="formData.competitionId"
            :min="1"
            :step="1"
            step-strictly
            placeholder="请输入赛事ID"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="赛事名称：" prop="competitionName">
          <el-input
            v-model.trim="formData.competitionName"
            maxlength="100"
            placeholder="请输入赛事名称"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="留言内容：" prop="context">
          <el-input
            v-model.trim="formData.context"
            type="textarea"
            :rows="4"
            maxlength="500"
            placeholder="请输入留言内容"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleClose">取消</el-button>
                 <el-button type="primary" @click="submitForm('formData')"
           >确定</el-button
         >
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog title="留言详情" :visible.sync="detailVisible" width="600px" :before-close="handleDetailClose">
      <div v-if="detailData" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ID">{{ detailData.id }}</el-descriptions-item>
          <el-descriptions-item label="赛事ID">{{ detailData.competitionId }}</el-descriptions-item>
          <el-descriptions-item label="赛事名称">{{ detailData.competitionName }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag 
              :type="detailData.checkStatus === 1 ? 'success' : 'warning'"
              size="small"
            >
              {{ detailData.checkStatus === 1 ? '已审核' : '未审核' }}
            </el-tag>
          </el-descriptions-item>
          
          <el-descriptions-item label="留言内容" :span="2">{{ detailData.context }}</el-descriptions-item>
          
          <!-- 只有当有回答时才显示回答内容 -->
          <el-descriptions-item v-if="detailData.child && detailData.child.length > 0" label="回答内容" :span="2">
            <div class="answer-content">
              <div v-for="(answer, index) in detailData.child" :key="index" class="answer-item">
                <div class="answer-header">
                  <span class="answer-time">{{ answer.createTime }}</span>
                </div>
                <div class="answer-text">{{ answer.context }}</div>
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer">
        <el-button @click="handleDetailClose">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 回答留言弹窗 -->
    <el-dialog title="回答留言" :visible.sync="answerVisible" width="600px" :before-close="handleAnswerClose">
      <el-form :model="answerForm" :rules="answerRules" ref="answerForm" label-width="100px">
        <el-form-item label="留言ID：">
          <el-input v-model="answerForm.leaveMessageId" disabled></el-input>
        </el-form-item>
        <el-form-item label="赛事ID：">
          <el-input v-model="answerForm.competitionId" disabled></el-input>
        </el-form-item>
        <el-form-item label="回答内容：" prop="context">
          <el-input
            v-model.trim="answerForm.context"
            type="textarea"
            :rows="6"
            maxlength="1000"
            placeholder="请输入回答内容"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleAnswerClose">取消</el-button>
        <el-button type="primary" @click="submitAnswer('answerForm')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// +---------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +---------------------------------------------------------------------
// | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
// +---------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +---------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +---------------------------------------------------------------------
import { checkPermi } from '@/utils/permission'; // 权限判断函数
import { leaveMessageSaveApi, leaveMessageListApi, leaveMessageDetailApi, leaveMessageDeleteApi, leaveMessageStatusApi, leaveMessageCheckApi, leaveMessageAnswerApi } from '@/api/leaveMessage';
import { handleDeleteTable } from '@/libs/public';
import { Debounce } from '@/utils/validate';

export default {
  name: 'LeaveMessage',
  data() {
    return {
      constants: this.$constants,
      tableFrom: {
        page: 1,
        limit: 20,
        competitionName: '',
        context: '',
      },
      loading: false,
      dialogVisible: false,
      detailVisible: false,
      detailData: null,
      dialogTitle: '新增留言',
      tableData: {
        data: [],
        total: 0,
      },
      formData: {
        competitionId: '',
        competitionName: '',
        context: '',
      },
      rules: {
        competitionId: [{ required: true, message: '请填写赛事ID', trigger: 'blur' }],
        competitionName: [{ required: true, message: '请填写赛事名称', trigger: 'blur' }],
        context: [{ required: true, message: '请填写留言内容', trigger: 'blur' }],
      },
      // 回答留言相关数据
      answerVisible: false,
      answerForm: {
        competitionId: '',
        leaveMessageId: '',
        context: '',
      },
      answerRules: {
        context: [{ required: true, message: '请填写回答内容', trigger: 'blur' }],
      },
    };
  },
  mounted() {
    console.log('留言提问页面已挂载');
    console.log('开始加载留言提问列表');
    this.getList(1);
  },
  methods: {
    checkPermi,
    // 新增
    handlerAdd() {
      this.dialogTitle = '新增留言';
      this.dialogVisible = true;
      this.formData = {
        competitionId: '',
        competitionName: '',
        context: '',
      };
    },
    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false;
      this.$refs.formData.resetFields();
    },
    // 重置表单
    resetForm() {
      this.tableFrom.competitionName = '';
      this.tableFrom.context = '';
      this.getList(1);
    },
    // 查看详情
    handleDetail(row) {
      this.detailVisible = true;
      this.loading = true;
      leaveMessageDetailApi(row.id)
        .then((res) => {
          this.detailData = res;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 关闭详情弹窗
    handleDetailClose() {
      this.detailVisible = false;
      this.detailData = null;
    },

    // 删除
    handleDelete(id) {
      this.$modalSure('删除该留言吗？').then(() => {
        leaveMessageDeleteApi(id).then(() => {
          this.$message.success('删除成功');
          handleDeleteTable(this.tableData.data.length, this.tableFrom);
          this.getList();
        });
      });
    },
    
    // 审核通过
    handleCheck(row) {
      this.$modalSure('确认审核通过该留言吗？').then(() => {
        const data = {
          id: row.id,
          checkStatus: 1
        };
        leaveMessageCheckApi(data).then(() => {
          this.$message.success('审核成功');
          this.getList();
        });
      });
    },

    // 回答留言
    handleAnswer(row) {
      this.answerForm = {
        competitionId: row.competitionId,
        leaveMessageId: row.id,
        context: '',
      };
      this.answerVisible = true;
    },

    // 关闭回答弹窗
    handleAnswerClose() {
      this.answerVisible = false;
      this.$refs.answerForm.resetFields();
      this.answerForm = {
        competitionId: '',
        leaveMessageId: '',
        context: '',
      };
    },

    // 提交回答
    submitAnswer: Debounce(function (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          leaveMessageAnswerApi(this.answerForm).then((res) => {
            this.$message.success('回答成功');
            this.handleAnswerClose();
            this.getList(); // 刷新列表
          }).catch((error) => {
            console.error('回答失败:', error);
            this.$message.error('回答失败，请重试');
          });
        } else {
          return false;
        }
      });
    }),
    // 列表
    getList(num) {
      this.loading = true;
      this.tableFrom.page = num ? num : this.tableFrom.page;
      console.log('开始请求留言提问列表，参数：', this.tableFrom);
      leaveMessageListApi(this.tableFrom)
        .then((res) => {
          console.log('留言提问列表请求成功：', res);
          this.tableData.data = res.list;
          this.tableData.total = res.total;
          this.loading = false;
        })
        .catch((error) => {
          console.error('留言提问列表请求失败：', error);
          this.loading = false;
        });
    },
    pageChange(page) {
      this.tableFrom.page = page;
      this.getList();
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val;
      this.getList();
    },
    // 表单提交
    submitForm: Debounce(function (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          leaveMessageSaveApi(this.formData).then((res) => {
            this.$message.success('新增成功');
            this.getList(1);
            this.handleClose();
          });
        } else {
          return false;
        }
      });
    }),
  },
};
</script>

<style scoped lang="scss">
.detail-content {
  .el-descriptions-item__label {
    width: 120px;
  }
}

.text-success {
  color: #67c23a;
  font-size: 12px;
}

.text-muted {
  color: #909399;
  font-size: 12px;
  font-style: italic;
}

.answer-content {
  .answer-item {
    margin-bottom: 15px;
    padding: 10px;
    background-color: #f8f9fa;
    border-radius: 4px;
    border-left: 3px solid #409eff;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .answer-header {
      margin-bottom: 8px;
      
      .answer-time {
        color: #909399;
        font-size: 12px;
      }
    }
    
    .answer-text {
      color: #303133;
      line-height: 1.5;
      word-break: break-all;
    }
  }
}
</style> 